// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { type = 'score', page = 1, pageSize = 20 } = event
  
  try {
    let orderBy = ''
    switch (type) {
      case 'score':
        orderBy = 'highestScore'
        break
      case 'win':
        orderBy = 'winCount'
        break
      case 'game':
        orderBy = 'gameCount'
        break
      default:
        return {
          success: false,
          error: '无效的排行榜类型'
        }
    }
    
    // 获取排行榜数据
    const leaderboard = await db.collection('users')
      .orderBy(orderBy, 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
    
    // 获取总用户数
    const count = await db.collection('users').count()
    
    // 获取当前用户排名
    const currentUser = await db.collection('users')
      .where({
        _openid: cloud.getWXContext().OPENID
      })
      .get()
    
    let currentRank = 0
    if (currentUser.data.length > 0) {
      const userScore = currentUser.data[0][orderBy] || 0
      const rank = await db.collection('users')
        .where({
          [orderBy]: db.command.gt(userScore)
        })
        .count()
      currentRank = rank.total + 1
    }
    
    return {
      success: true,
      data: {
        leaderboard: leaderboard.data,
        total: count.total,
        page,
        pageSize,
        currentRank,
        currentUser: currentUser.data[0]
      }
    }
  } catch (error) {
    console.error('获取排行榜失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 